package com.mazong.servershirobb.controller;

import com.mazong.servershirobb.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Slf4j
@Controller
public class ShiroController {

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/login")
    public String login(TbUser user, Model model) {
        //--
        if(user == null || user.getUsername() == null) {
            return "login";
        }

        //--
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        try {
            subject.login(token);
        }
        catch (UnknownAccountException e) {
            log.info("用户名不存在");
            model.addAttribute("msg", "用户名不存在");
            return "/login";
        }
        catch (IncorrectCredentialsException e) {
            log.info("密码不正确");
            model.addAttribute("msg", "密码不正确");
            return "/login";
        }

        return "/index";
    }

    @RequestMapping(value = "/403")
    public String page403() {
        return "/403";
    }

    @RequestMapping(value = "/product/select")
    public String select() {
        return "/product/select";
    }

    @RequestMapping(value = "/product/insert")
    public String insert() {
        return "/product/insert";
    }

    @RequestMapping(value = "/product/update")
    public String update() {
        return "/product/update";
    }

    @RequestMapping(value = "/product/delete")
    public String delete() {
        return "/product/delete";
    }

    @RequestMapping(value = "/logout")
    public String logout(Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");

        return "login";
    }
}
